/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.max.cjs.bean;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.max.cjs.model.Schedule;
import org.max.cjs.service.interfac.IScheduleService;
import org.max.cjs.util.Clazz;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;

/**
 *
 * @author user
 */
@ManagedBean
@ViewScoped
public class ScheduleClientBean implements Serializable {
    
    @ManagedProperty("#{scheduleService}")
    IScheduleService scheduleService;
    //private String linkShare = "if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open(&#039;http://www.cjavaperu.com/informe/client.php?locale=es&amp;url=&#039;+escape(document.location.href)+&#039;&amp;referrer=&#039;+escape(document.referrer), 'mibew', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');this.newWindow.focus();this.newWindow.opener=window;return false;";
    private String linkShare = "if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 && window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open('http://www.cjavaperu.com/informe/client.php?locale=es&amp;url='+escape(document.location.href)+'&referrer='+escape(document.referrer), 'mibew', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');this.newWindow.focus();this.newWindow.opener=window;return false;";
    private String image = null;
    private ScheduleModel lazyEventModel;
    private Schedule schedule = new Schedule();
    private List<String> listMonth;
    @PostConstruct
    public void initVar() {
        selectImage();
    }
    
    private void selectImage() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);

        if (month == Calendar.JANUARY) {
            image = capturePathMonth("ENERO");
        } else if (month == Calendar.FEBRUARY) {
            image = capturePathMonth("FEBRERO");
        } else if (month == Calendar.MARCH) {
            image = capturePathMonth("MARZO");
        } else if (month == Calendar.APRIL) {
            image = capturePathMonth("ARBIL");
        } else if (month == Calendar.MAY) {
            image = capturePathMonth("MAYO");
        } else if (month == Calendar.JUNE) {
            image = capturePathMonth("JUNIO");
        } else if (month == Calendar.JULY) {
            image = capturePathMonth("JULIO");
        } else if (month == Calendar.AUGUST) {
            image = capturePathMonth("AGOSTO");
        } else if (month == Calendar.SEPTEMBER) {
            image = capturePathMonth("SETIEMBRE");
        } else if (month == Calendar.OCTOBER) {
            image = capturePathMonth("OCTUBRE");
        } else if (month == Calendar.NOVEMBER) {
            image = capturePathMonth("NOVIEMBRE");
        } else if (month == Calendar.DECEMBER) {
            image = capturePathMonth("DICIEMBRE");
        }
    }
    
    private String capturePathMonth(String month) {
        String last = "";
        for (int i = 0; i < getListMonth().size(); i++) {
            String[] part = getListMonth().get(i).split("-");
            if (part[0].startsWith(month)) {
                last = "resources/images/" + getListMonth().get(i);
            }
        }
        return last;
    }
    
    public List<String> getListMonth() {
        if (listMonth == null) {
            String remov = FacesContext.getCurrentInstance().getExternalContext()
                    .getRealPath("/") + "resources/images/";
            listMonth = new ArrayList<>(Arrays.asList(new File(remov.replace("/", File.separator)).list()));

        }
        return listMonth;
    }

    public String getLinkShare() {
        return linkShare;
    }

    public void setLinkShare(String linkShare) {
        this.linkShare = linkShare;
    }

    public void setScheduleService(IScheduleService scheduleService) {
        this.scheduleService = scheduleService;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
    
    public void onEventSelect(SelectEvent selectEvent) throws Exception {
        ScheduleEvent eventTemp = (ScheduleEvent) selectEvent.getObject();
        schedule = scheduleService.getByHQL("from Schedule s where s.name='(name)' and s.dayActive='(day)'"
                .replace("(name)", eventTemp.getTitle())
                .replace("(day)", eventTemp.getStartDate() + ""));
    }

    public Schedule getSchedule() {
        return schedule;
    }

    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }
    
    
    public ScheduleModel getLazyEventModel() {

        if (lazyEventModel == null) {
            lazyEventModel = new LazyScheduleModel() {
                @Override
                public void loadEvents(Date start, Date end) {
                    try {
                        String hql = "select s.id as id, s.name as name, s.state as state, s.dayActive as dayActive, s.type as type from Schedule s where"
                                + " s.state='(state)' and s.dayActive BETWEEN :start and :end";
                        hql = hql.replace("(state)", Clazz.STATE.ACTIVO);
                        List<Date> listParam = new ArrayList<>();
                        listParam.add(start);
                        listParam.add(end);
                        List<Schedule> list = scheduleService.listHQL(hql, 1, listParam);
                        DefaultScheduleEvent d;
                        for (Schedule schedule : list) {
                            
                            if (schedule.getType() != null && schedule.getType().equals(Clazz.TYPE.EVENTO)) {
                                addEvent(new DefaultScheduleEvent(schedule.getName(), schedule.getDayActive(), schedule.getDayActive(), "public-event-evento"));
                            } else if (schedule.getType() != null && schedule.getType().equals(Clazz.TYPE.INICIO_CURSO)) {
                                addEvent(new DefaultScheduleEvent(schedule.getName(), schedule.getDayActive(), schedule.getDayActive(), "public-event-curso"));
                            } else if (schedule.getType() != null && schedule.getType().equals(Clazz.TYPE.SORTEO)) {
                                addEvent(new DefaultScheduleEvent(schedule.getName(), schedule.getDayActive(), schedule.getDayActive(), "public-event-sorteo"));
                            } else {
                                addEvent(new DefaultScheduleEvent(schedule.getName(), schedule.getDayActive(), schedule.getDayActive()));
                            }
                        }

                    } catch (Exception ex) {
                        Logger.getLogger(ScheduleBean.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
        }
        return lazyEventModel;
    }
    
}
